/**
 * Created by waterworld on 17-4-9.
 */
/**
 * Created by waterworld on 17-3-5.
 */
//name type Stirng
var stateMachine = function(name) {
    this.cbMap={};
    this.name=name;
    this.currentState='';
    return this;
};
stateMachine.prototype.setTurnTime=function(t)
{
    this.turnTime=t;

};
//name 回调事件名称   cb回调函数 time回调事件间隔
stateMachine.prototype.setCallback=function(name,cb,time)
{
    if(!cb) return;
    var it=this.cbMap[name];
    if(time==undefined) time=10;
    if(!it)
        this.cbMap[name]={cb:cb,time:time,tick:process.uptime()};//默认一秒钟调用一次
    if(typeof time=='number'&&it)
    {
        it.tick=process.uptime();
        it.time=time;
    }
}

stateMachine.prototype.setCurrentState=function(stateName)
{
    this.currentState=stateName;
}

stateMachine.prototype.changeState=function(stateName)
{
    this.currentState=stateName;
    this.resetTick(stateName);
}
stateMachine.prototype.getStateTime=function(stateName)
{
    var it=this.cbMap[stateName];
    if(it) return it.time;
    return 0;

}
stateMachine.prototype.cancelCallback=function(name)
{    this.cbMap[name]=null;
}

stateMachine.prototype.resetAlltick=function()
{
    for(var name in this.cbMap)
    {
        var it=this.cbMap[name];
        if(it&&it.cb)
        { it.tick=process.uptime();}
    }
}

stateMachine.prototype.resetTick=function(name)
{
    var it=this.cbMap[name];
    if(it) it.tick=process.uptime();
}
stateMachine.prototype.eventChange=function(event)
{
    this.event=event;
};

stateMachine.prototype.onLoop=function()
{
     var it=this.cbMap[this.currentState];
    if(it&&it.cb)
    {  var time=process.uptime()-it.tick;
        if(time>=it.time)
        { var exit=it.cb();
            it.tick=process.uptime();
        }
    }

};

stateMachine.prototype.onLoop1=function()
{
    for(var name in this.cbMap)
    {
        var it=this.cbMap[name];
        if(it&&it.cb)
        {  var time=process.uptime()-it.tick;
            if(time>=it.time)
            {   var exit=it.cb();
                it.tick=process.uptime();
                if(exit==true) return;
            }
        }
    }
};

module.exports=stateMachine;
